package com.leizhi.demo.monitor.achieve;

import lombok.Getter;
import org.springframework.lang.NonNull;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * @Description 同步等待结果
 * @Version 1.0.0-SNAPSHOT
 * @Author leizhi
 * @Date 2025/4/27 11:50
 */
public class SyncFuture<T> implements Future<T> {

    /* 响应结果 */
    private T response;

    /* 等待响应结果锁 */
    private final CountDownLatch latch = new CountDownLatch(1);

    /* 请求开始时间 */
    @Getter
    private final long beginTime = System.currentTimeMillis();


    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        return false;
    }

    @Override
    public boolean isCancelled() {
        return false;
    }

    @Override
    public boolean isDone() {
        return response != null;
    }

    // 获取响应结果，直到有结果才返回。
    @Override
    public T get() throws InterruptedException {
        latch.await();
        return this.response;
    }

    // 获取响应结果，直到有结果或者超过指定时间就返回。
    @Override
    public T get(long timeout, @NonNull TimeUnit unit) throws InterruptedException {
        if (latch.await(timeout, unit)) {
            return this.response;
        }
        return null;
    }

    // 用于设置响应结果，并且做countDown操作，通知请求线程
    public void setResponse(T response) {
        this.response = response;
        latch.countDown();
    }

}
